package microphone;

import com.sun.media.sound.AudioFloatConverter;
import edu.emory.mathcs.jtransforms.fft.FloatFFT_1D;
import javax.sound.sampled.AudioFormat;

/**
 *
 * @author Tom
 */
public class AudioProcessing {

    private static FloatFFT_1D fft;

    public static short[] forward(float[] data) {
        int N = data.length;
        short[] sData = new short[N];
        /* for (int i = 0; i < data.length; i++) {
        data[i] *= hannWindow(i, N);            
        } */

        fft = new FloatFFT_1D(N);
        fft.realForward(data);
        int k = 0;
        for (int i = 0; i < data.length; i++) {



            if (i < (1 * data.length) / 5) {
                if (Math.abs(data[i]) < 3) {
                    //System.out.println(data[i]);
                    data[i] = 0;
                    k++;
                }
            } else if (i > (3 * data.length) / 5) {
                if (Math.abs(data[i]) < 3) {
                    //System.out.println(data[i]);
                    data[i] = 0;
                    k++;
                }
            } else {
                data[i] = Math.round(data[i]);
            }

            sData[i] = (short) data[i];
        }
        return sData;
    }

    public static byte[] inverse(float[] data, AudioFormat af) {
        int N = data.length;
        fft = new FloatFFT_1D(N);
        fft.realInverse(data, true);

        /*for (int i = 0; i < data.length; i++) {
        data[i] *= 1 / hannWindow(i, N);
        }*/

        AudioFloatConverter conv = AudioFloatConverter.getConverter(af);
        byte[] bytes = new byte[data.length * 2];
        conv.toByteArray(data, bytes);
        return bytes;
    }

    private static float hannWindow(int n, int N) {
        return 1.0f;
        //float secPart = 1.0f - (float) Math.cos((2.0f * Math.PI * (float) n) / (float) (N - 1));
        //return (0.5f * secPart);
    }
}
